import {
  ExceptionFilter,
  Catch,
  ArgumentMetadata,
  HttpException,
  ArgumentsHost,
} from '@nestjs/common';
import { Request, Response } from 'express';

// 异常装饰器
@Catch(HttpException)
export class HttpFilter implements ExceptionFilter {
  // exception: 异常信息
  // host：请求信息
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    // 请求参数
    const req = ctx.getRequest<Request>();
    // 响应参数
    const res = ctx.getResponse<Response>();
    // 状态码
    const status = exception.getStatus();
    const info = {
      success: false,
      time: new Date(),
      data: exception.getResponse()['message'],
      status,
      path: req.url,
    };
    console.log('异常', info);
    // 设置响应数据
    res.status(status).json(info);
  }
}
